<template>
  <view class="recharge-container">
    <!-- 余额信息 -->
    <view class="balance-section">
      <view class="title">当前余额</view>
      <view class="balance">
        <text class="amount">{{ balance }}</text>
        <text class="unit">元</text>
      </view>
    </view>

    <!-- 充值金额选择 -->
    <view class="amount-section">
      <view class="section-title">充值金额</view>
      <view class="amount-options">
        <view
          v-for="amount in rechargeAmounts"
          :key="amount"
          class="amount-option"
          :class="{ active: selectedAmount === amount && !isCustomAmount }"
          @click="selectAmount(amount)"
        >
          <text class="amount">{{ amount }}元</text>
        </view>
        <view class="amount-option custom" :class="{ active: isCustomAmount }">
          <input
            type="number"
            v-model="customAmount"
            class="custom-input"
            placeholder="其他金额"
            @focus="activateCustomAmount"
            @blur="validateCustomAmount"
          />
        </view>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-section">
      <view class="section-title">支付方式</view>
      <view class="payment-methods">
        <view class="payment-method" @click="selectedPayMethod = 'wxpay'">
          <view class="method-info">
            <image class="method-icon" src="/static/wallet/wxpay.png" mode="aspectFit" />
            <text class="method-name">微信支付</text>
          </view>
          <view class="method-selected" v-if="selectedPayMethod === 'wxpay'">
            <text class="selected-icon">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 充值按钮 -->
    <view class="button-section">
      <button
        class="recharge-button"
        :class="{ disabled: !canRecharge }"
        @click="handleRecharge"
      >
        确认充值
      </button>
      <view class="agreement">
        <text>点击充值即表示同意</text>
        <text class="link" @click="viewAgreement">《{{ policy.name || '充值服务协议' }}》</text>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      selectedAmount: null,
      customAmount: '',
      isCustomAmount: false,
      rechargeAmounts: [],
      selectedPayMethod: 'wxpay',
      minRechargeAmount: 0,
      maxRechargeAmount: 0,
      policy: {}
    }
  },
  computed: {
    ...mapGetters(['balance']),
    canRecharge() {
      const amount = this.isCustomAmount ? parseFloat(this.customAmount) : this.selectedAmount
      return amount > 0 && amount <= this.maxRechargeAmount
    }
  },
  onLoad() {
    this.$api.getPolicyList({
      type: '1'
    }).then(res => {
      if (res.length) {
        this.policy = res[0]
      }
    })
    this.getConfig()
  },
  methods: {
    async getConfig() {
      uni.showLoading()
      try {
        const res1 = await this.$api.getConfig({
          code: 'min_recharge_amount'
        })
        this.minRechargeAmount = Number(res1 || 0)
        const res2 = await this.$api.getConfig({
          code: 'max_recharge_amount'
        })
        this.maxRechargeAmount = Number(res2 || 0)

        const res3 = await this.$api.getConfig({
          code: 'recharge_amounts'
        })
        console.log('res3',res3)
        this.rechargeAmounts = (res3 || '').split(',').map(amount => Number(amount))
      } catch (e) {
        uni.hideLoading()
        console.error(e)
      }
    },
    selectAmount(amount) {
      this.selectedAmount = amount
      this.isCustomAmount = false
      this.customAmount = ''
    },
    activateCustomAmount() {
      this.isCustomAmount = true
      this.selectedAmount = 0
    },
    validateCustomAmount() {
      const amount = parseFloat(this.customAmount)
      if (this.customAmount === '') {
        this.isCustomAmount = false
        this.selectedAmount = 0
        return
      }

      if (isNaN(amount) || amount < this.minRechargeAmount) {
        uni.showToast({
          title: `最小充值金额为${this.minRechargeAmount}元`,
          icon: 'none'
        })
        this.customAmount = ''
        this.isCustomAmount = false
        this.selectedAmount = 0
        return
      }

      if (amount > this.maxRechargeAmount) {
        uni.showToast({
          title: `单次最大充值金额为${this.maxRechargeAmount}元`,
          icon: 'none'
        })
        this.customAmount = ''
        this.isCustomAmount = false
        this.selectedAmount = 0
        return
      }

      this.selectedAmount = amount
      this.isCustomAmount = true
    },
    handleRecharge() {
      if (!this.canRecharge) {
        return
      }

      const amount = this.isCustomAmount ? parseFloat(this.customAmount) : this.selectedAmount

      uni.showModal({
        title: '充值确认',
        content: `确认充值${amount}元到账户余额？`,
        confirmText: '确认',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.processRecharge(amount)
          }
        }
      })
    },
    processRecharge(amount) {
      // TODO: 调用充值接口
      console.log('开始充值', {
        amount,
        payMethod: this.selectedPayMethod
      })
      uni.showLoading({
        title: '正在充值...'
      })
      this.$api.recharge({
        payOrderType: 'order_top_up',
        amount: this.isCustomAmount ? this.customAmount : this.selectedAmount,
        description: '余额充值'
      }).then(res => {
        let {
          nonceStr,
          packageVal,
          signType,
          paySign,
          timeStamp
        } = res
        uni.requestPayment({
          timeStamp,
          nonceStr,
          package: packageVal,
          signType,
          paySign,
          success: (res) => {
            console.log('支付成功', res)
            uni.showToast({
              title: '充值成功',
              icon: 'success'
            })
            setTimeout(() => {
              uni.navigateBack()
            },800)
          },
          fail: (err) => {
            console.error('支付失败', err)
            uni.showToast({
              title: '支付失败',
              icon: 'none'
            })
          },
        })
      })
    },
    viewAgreement() {
      // TODO: 查看充值协议
      uni.navigateTo({
        url: '/pages/policy/policy?id=' + this.policy.id
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.recharge-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 120rpx;
}

.balance-section {
  background: #FFFFFF;
  padding: 48rpx 32rpx;
  text-align: center;

  .title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 16rpx;
  }

  .balance {
    .amount {
      font-size: 64rpx;
      font-weight: 500;
      color: #333;
    }

    .unit {
      font-size: 28rpx;
      color: #666;
      margin-left: 8rpx;
    }
  }
}

.amount-section {
  margin-top: 24rpx;
  padding: 32rpx;
  background: #FFFFFF;

  .section-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 24rpx;
  }

  .amount-options {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24rpx;

    .amount-option {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #F8F9FC;
      border-radius: 12rpx;
      border: 2rpx solid transparent;

      &.active {
        background: rgba(4, 200, 174, 0.05);
        border: 2rpx solid #04C8AE;
        color: #04C8AE;
      }

      &.custom {
        padding: 0;

        .custom-input {
          width: 100%;
          height: 88rpx;
          padding: 0 24rpx;
          font-size: 28rpx;
          color: #333;
          background: #F8F9FC;
          border: 2rpx solid #EBEDF0;
          border-radius: 12rpx;
          text-align: center;

          &::placeholder {
            color: #999;
          }
        }

        &.active .custom-input {
          border-color: #04C8AE;
          background: rgba(4, 200, 174, 0.05);
        }
      }
    }
  }
}

.payment-section {
  margin-top: 24rpx;
  padding: 32rpx;
  background: #FFFFFF;

  .section-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 24rpx;
  }

  .payment-methods {
    .payment-method {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx 0;

      .method-info {
        display: flex;
        align-items: center;

        .method-icon {
          width: 48rpx;
          height: 48rpx;
          margin-right: 16rpx;
        }

        .method-name {
          font-size: 28rpx;
          color: #333;
        }
      }

      .method-selected {
        .selected-icon {
          color: #04C8AE;
          font-size: 32rpx;
        }
      }
    }
  }
}

.button-section {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 32rpx;
  background: #FFFFFF;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  padding-bottom: 80rpx;

  .recharge-button {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #04C8AE;
    color: #FFFFFF;
    font-size: 32rpx;
    border-radius: 44rpx;
    border: none;
    margin-bottom: 24rpx;

    &.disabled {
      background: #CCCCCC;
      opacity: 0.6;
    }
  }

  .agreement {
    text-align: center;
    font-size: 24rpx;
    color: #999;

    .link {
      color: #04C8AE;
    }
  }
}
</style>
